package com.ouroboroswiki.core.content;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ouroboroswiki.core.AbstractContentRepositoryProxy;
import com.ouroboroswiki.core.Content;
import com.ouroboroswiki.core.ContentException;
import com.ouroboroswiki.core.ContentPath;
import com.ouroboroswiki.core.ContentUtil;
import com.ouroboroswiki.core.Version;
import com.ouroboroswiki.core.VersionBuilder;

public class ToBasePathsContentRepositoryProxy extends
		AbstractContentRepositoryProxy {

	@Override
	public Content getContent(Object principal, ContentPath path,
			Version version, Map<String, Object> properties)
			throws ContentException {
		List<ContentPath> splits = ContentUtil.split(path);
		Map<String, Content> contents = new HashMap<String, Content>(splits.size());
		boolean exists = false;
		boolean writable = splits.size() == 1;
		String mimeType = null;
		StringBuffer name = new StringBuffer();
		if( splits.size() > 1 ) {
			name.append('(');
		}
		for( int i = 0; i<splits.size(); i++ ) {
			ContentPath split = splits.get(i);
			ContentPath basePath = split.getBasePath();
			Content content = proxied.getContent(
					principal, 
					basePath, 
					version, 
					properties
			);
			String contentMimeType = content.getMimeType();
			if( contentMimeType != null ) {
				mimeType = contentMimeType;
			}
			exists = exists || content.exists();
			writable = writable && content.isWritable();
			String id;
			if( i == 0 ) {
				id = Content.CHILD_CONTENT_MAIN;
			} else {
				id = basePath.getName();
			}
			contents.put( id, content );
			name.append( basePath.getName() );
			if( i == splits.size()-1 ) {
				if( i != 0 ) {
					name.append(')');
				}
			} else {
				name.append('|');
			}
		}
		CompositeContent result = new CompositeContent( contents );
		result.setRepositoryName( this.getName() );
		
		result.setUniqueName(name.toString());
		result.setExists(exists);
		result.setWritable(writable);
		result.setMimeType(mimeType);
		return result;
	}

	@Override
	public boolean exists(Object principal, ContentPath path)
			throws ContentException {
		boolean result = false;
		List<ContentPath> splits = ContentUtil.split(path);
		for( int i = 0; i<splits.size(); i++ ) {
			ContentPath split = splits.get(i);
			ContentPath basePath = split.getBasePath();
			result = result || proxied.exists(principal, basePath);
		}
		return result;		
	}

	@Override
	public Version buildVersion(Object principal, ContentPath path,
			String[] versionPath, VersionBuilder versionBuilder)
			throws ContentException {
		// TODO Auto-generated method stub
		return null;
	}

}
